//
//  BaoxiuPickPicView.swift
//  Xiaozihui
//
//  Created by 校企荟 on 2017/10/18.
//  Copyright © 2017年 校企荟. All rights reserved.
//

import UIKit
import TZImagePickerController


class BaoxiuPickPicView: UIView {

    var selectedPhotos : [Any]?
    var selectedAssets : [Any]?
    
   
    lazy var addressLbl: UILabel = {
        let lbl = UILabel(content: "上传照片(非必选)", textFont: UIFont.boldSystemFont(ofSize: 15 * ScaleX), color: #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1), alignment: .left, numberOfLine: 0)
        return lbl
    }()
    

    lazy var collectionView: UICollectionView = {
        let fl = UICollectionViewFlowLayout()
        let width = 90 * ScaleX
        let margin = ((ScreenWidth - 100) - width * 3) / 2
        fl.itemSize = CGSize(width: width, height: width)
        fl.minimumLineSpacing = margin
        fl.minimumInteritemSpacing = margin
        let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: fl)
        cv.register(TZTestCell.self, forCellWithReuseIdentifier: "cell")
        cv.dataSource = self
        cv.delegate = self
        cv.backgroundColor = UIColor.white
        cv.isScrollEnabled = false
        return cv
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)

        isUserInteractionEnabled = true
        addSubview(addressLbl)
        addSubview(collectionView)

        addressLbl.snp.makeConstraints { (make) in
            make.top.equalTo(self).offset(15)
            make.left.equalTo(self).offset(50)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(addressLbl.snp.bottom).offset(10)
            make.left.equalTo(addressLbl)
            make.right.equalTo(self).offset(-50)
            make.height.equalTo(90 * ScaleX)
            make.bottom.equalTo(self)
        }
        
    }
    
 
    
    func presentPicker() {
        let picker =  TZImagePickerController(maxImagesCount: 3, columnNumber: 4, delegate: self)
        UIApplication.shared.keyWindow?.rootViewController?.present(picker!, animated: true, completion: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension BaoxiuPickPicView:TZImagePickerControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource {
    
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {
        selectedPhotos = photos
        selectedAssets = assets
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if selectedPhotos?.count == 3 {
            return 3
        }
        return (selectedPhotos?.count ?? 0) + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! TZTestCell
//        cell.imageView.isUserInteractionEnabled = false
//        cell.deleteBtn.isEnabled = false
//        cell.videoImageView.isUserInteractionEnabled = false
        if indexPath.row == (selectedPhotos?.count ?? 0) {
            cell.imageView.image = #imageLiteral(resourceName: "Release_Add")
            cell.deleteBtn.isHidden = true
        } else {
            cell.imageView.image = selectedPhotos?[indexPath.row] as? UIImage
            cell.imageView.layer.borderWidth = 1;
            cell.imageView.layer.borderColor = UIColor.groupTableViewBackground.cgColor
            cell.imageView.contentMode = .scaleAspectFit
            cell.deleteBtn.isHidden = false
            
            
        }
        
        cell.deleteBtn.tag = indexPath.row
        cell.deleteBtn.addTarget(self, action: #selector(deleteBtnClick(btn:)), for: .touchUpInside)
        
        return cell
    }
    
    func deleteBtnClick(btn:UIButton){
        selectedPhotos?.remove(at: btn.tag)
        selectedAssets?.remove(at: btn.tag)
        
        collectionView.performBatchUpdates({
            let indexPath = NSIndexPath(item: btn.tag, section: 0)
            collectionView.deleteItems(at: [indexPath as IndexPath])
        }) { (finished) in
            self.collectionView.reloadData()
        }
    }
    

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.row == (selectedPhotos?.count ?? 0) {
            presentPicker()
        }
        print("点击了")
    }
    
    

}
